package lib.bone.admin.controller.nepu;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Validator;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lib.bone.access.config.cycle.NepuCycle;
import lib.bone.access.config.cycle.NepuCycleService;
import lib.bone.access.constant.ResearchTypeConst;
import lib.bone.access.constant.WorkloadSourceConst;
import lib.bone.access.constant.WorkloadTypeConst;
import lib.bone.access.module.post.NepuPostService;
import lib.bone.access.module.userpost.NepuUserPostService;
import lib.bone.admin.anno.WebLog;
import lib.bone.admin.constant.MethodTypeConst;
import lib.bone.audit.workload.attach.ResearchAttach;
import lib.bone.audit.workload.domain.NepuWorkload;
import lib.bone.audit.workload.domain.WorkloadUseLog;
import lib.bone.audit.workload.domain.dto.*;
import lib.bone.audit.workload.listener.AddWorkloadListener;
import lib.bone.audit.workload.listener.AddWorkloadXListener;
import lib.bone.audit.workload.listener.ManageWorkloadListener;
import lib.bone.audit.workload.listener.TeachingWorkloadListener;
import lib.bone.audit.workload.service.NepuWorkloadService;
import lib.bone.audit.workload.service.WorkloadUseLogService;
import lib.bone.common.constant.ResponseCodeConst;
import lib.bone.common.core.domain.ResponseDTO;
import lib.bone.common.utils.JsonUtil;
import lib.bone.nepudata.domain.entity.*;
import lib.bone.nepudata.service.ResearchServiceCtl;
import lib.bone.system.domain.entity.SysUser;
import lib.bone.system.domain.vo.SysUserBasic;
import lib.bone.system.module.iojob.domain.IOJob;
import lib.bone.system.module.iojob.service.IOJobService;
import lib.bone.system.service.SysDeptService;
import lib.bone.system.service.SysUserRoleService;
import lib.bone.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("nepu")
@Api(tags = "工作量记录")
public class NepuWorkloadController {
    @Value("${file-upload-service.path}")
    private String fileParentPath;

    @Autowired
    NepuWorkloadService nepuWorkloadService;

    @Autowired
    WorkloadUseLogService logService;

    @Autowired
    SysDeptService deptService;

    @Autowired
    SysUserRoleService sysUserRoleService;

    @Autowired
    ResearchServiceCtl researchServiceCtl;

    @Autowired
    NepuCycleService cycleService;

    @Autowired
    SysUserService userService;

    @Autowired
    NepuPostService nepuPostService;

    @Autowired
    NepuUserPostService nepuUserPostService;

    @Autowired
    IOJobService ioJobService;


    @PostMapping("workload/fix/topic")
    @ApiOperation(value = "纵向课题工作量全修复")
    public ResponseDTO<Object> fixWorkloads(){
        NepuWorkload nepuWorkload = new NepuWorkload(WorkloadTypeConst.RESEARCH, WorkloadSourceConst.APPLY);
        Example<NepuWorkload> example = Example.of(nepuWorkload);
        List<NepuWorkload> workloads = nepuWorkloadService.finAll(example);

        workloads = workloads.stream().filter(ele->{
            ResearchAttach attach = JsonUtil.string2Obj(ele.getWorkloadAttach(),ResearchAttach.class);
            return attach != null && attach.getResearchType().equals(ResearchTypeConst.TOPIC) && ele.getWorkloadType().equals(WorkloadTypeConst.RESEARCH);
        }).collect(Collectors.toList());

        workloads.forEach(ele->{
            nepuWorkloadService.fixWorkload(ele);
        });

        return ResponseDTO.succMsg("调用修复任务");
    }


    // fix 获奖相关的工作量 的 attach 里面的 dictName

//    @WebLog(module = "bone-system")
    @PostMapping("workloads/teaching/import")
    @ApiOperation(value = "教学工作量导入")
    public ResponseDTO teachingWorkloadImport(MultipartFile file,@RequestParam("cycleId") String cycleId) throws IOException {
        Optional<NepuCycle> cycleOp = cycleService.getById(cycleId);
        // 新建导入任务
        IOJob ioJob = ioJobService.createImportJob();
        if (!cycleOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        NepuCycle cycle = cycleOp.get();
        String parentCycleId = cycle.getParentId();
        EasyExcel.read(file.getInputStream(), TeachingWorkloadImportDTO.class, new TeachingWorkloadListener(userService,deptService,nepuWorkloadService,ioJobService,cycleId,parentCycleId, ioJob.getId(), fileParentPath)).sheet(0).doRead();
        return ResponseDTO.succMsg("写入成功");
    }

    @PostMapping("workloads/manage/import")
    @ApiOperation(value = "管理工作量导入")
    public ResponseDTO manageWorkloadImport(MultipartFile file,@RequestParam("cycleId") String cycleId) throws IOException {
        Optional<NepuCycle> cycleOp = cycleService.getById(cycleId);
        // 新建导入任务
        IOJob ioJob = ioJobService.createImportJob();
        if (!cycleOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        NepuCycle cycle = cycleOp.get();
        String parentCycleId = cycle.getParentId();
        EasyExcel.read(file.getInputStream(), ManageWorkloadImportDTO.class, new ManageWorkloadListener(userService,deptService,nepuWorkloadService,ioJobService,cycleId,parentCycleId, ioJob.getId(), fileParentPath)).sheet(0).doRead();
        return ResponseDTO.succMsg("写入成功");
    }

//    @WebLog(module = "bone-system")
    @PostMapping("workloads/add/import")
    @ApiOperation(value = "追加工作量导入")
    public ResponseDTO AddWorkloadImport(MultipartFile file,@RequestParam("cycleId") String cycleId) throws IOException {
        log.info("导入任务开始！");
        Optional<NepuCycle> cycleOp = cycleService.getById(cycleId);
        // 新建导入任务
        IOJob ioJob = ioJobService.createImportJob();
        log.info("导入任务创建结束！");
        if (!cycleOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        log.info("周期不为空！");
        NepuCycle nepuCycle = new NepuCycle();
        BeanUtil.copyProperties(cycleOp.get(),nepuCycle,CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        String cycleName = nepuCycle.getCycleName();
        String parentCycleId=nepuCycle.getParentId();
        EasyExcel.read(file.getInputStream(), SupplementImportDTO.class, new AddWorkloadListener(userService,nepuWorkloadService,ioJobService,cycleName,cycleId,parentCycleId,ioJob.getId(), fileParentPath)).sheet(0).doRead();
        return ResponseDTO.succMsg("写入成功");
    }

    @PostMapping("workloads/add/importX")
    @ApiOperation(value = "追加工作量导入(新版本)")
    public ResponseDTO AddWorkloadImportX(MultipartFile file,@RequestParam("cycleId") String cycleId) throws IOException {
        log.info("导入任务开始！");
        Optional<NepuCycle> cycleOp = cycleService.getById(cycleId);
        // 新建导入任务
        IOJob ioJob = ioJobService.createImportJob();
        log.info("导入任务创建结束！");
        if (!cycleOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        log.info("周期不为空！");
        NepuCycle nepuCycle = new NepuCycle();
        BeanUtil.copyProperties(cycleOp.get(),nepuCycle,CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        String cycleName = nepuCycle.getCycleName();
        String parentCycleId=nepuCycle.getParentId();
        if (nepuCycle.getParentId()==null){
            parentCycleId = nepuCycle.getId();
        }
        EasyExcel.read(file.getInputStream(), SupplementImportXDTO.class, new AddWorkloadXListener(userService,nepuWorkloadService,ioJobService,cycleName,cycleId,parentCycleId,ioJob.getId(), fileParentPath)).sheet(0).doRead();
        return ResponseDTO.succMsg("写入成功");
    }

    @PostMapping("workloads/award/import")
    @ApiOperation(value = "教学获奖导入")
    public ResponseDTO awardImport(MultipartFile file,@RequestParam("cycleId") String cycleId) throws IOException {
        Optional<NepuCycle> cycleOp = cycleService.getById(cycleId);
        // 新建导入任务
        IOJob ioJob = ioJobService.createImportJob();
        if (!cycleOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        NepuCycle cycle = cycleOp.get();
        String parentCycleId = cycle.getParentId();
        EasyExcel.read(file.getInputStream(), TeachingWorkloadImportDTO.class, new TeachingWorkloadListener(userService,deptService,nepuWorkloadService,ioJobService,cycleId,parentCycleId, ioJob.getId(), fileParentPath)).sheet(0).doRead();
        return ResponseDTO.succMsg("写入成功");
    }


//    WorkloadUseLog teachUseLog(String cycleId,Long userId, Double workload, String useMethod){
//        WorkloadUseLog useLog = new WorkloadUseLog();
//        useLog.setCycleId(cycleId);
//        useLog.setUserId(userId);
//        useLog.setWorkload(workload);
//        useLog.setUseMethod(useMethod);
//        return useLog;
//    }
//
//    @ApiIgnore
//    @PostMapping("worloads/{userId}/teachdeduction")
//    @ApiOperation(value = "教学工作量冲抵")
//    public void workloadDeduction(@PathVariable("userId") Long userId){
//        List<NepuWorkload> teachWorkloadList = nepuWorkloadService.findByUserIdAndWorkloadTypeAndUsedUpOrderByWorkloadAsc(userId,WorkloadTypeConst.TEACH,0);
//        Double teachworkload = 0.0;
//        System.out.println("teachWorkloadList:"+teachWorkloadList);
//        List<WorkloadUseLog> workloadUseLogList = new ArrayList<>();
//        Optional<NepuUserPost> nepuUserPostOp = nepuUserPostService.findByUserId(userId);
//        NepuUserPost nepuUserPost = nepuUserPostOp.get();
//        Optional<NepuPost> nepuPostOp = nepuPostService.getById(nepuUserPost.getPostId());
//        NepuPost nepuPost = nepuPostOp.get();
//        double teachTargetWorkload = nepuPost.getTeachWorkload();
//        System.out.println("teachTargetWorkload:"+teachTargetWorkload);
//        for (NepuWorkload nepuWorkload:teachWorkloadList){
//            //若本条教学工作量记录全部使用不会超过目标教学工作量
//            if (teachworkload+(nepuWorkload.getWorkload()-nepuWorkload.getUsedWorkload())<=teachTargetWorkload){
//                teachworkload += (nepuWorkload.getWorkload() - nepuWorkload.getUsedWorkload());
//                WorkloadUseLog teachTargetLog = teachUseLog(nepuWorkload.getCycleId(),userId,nepuWorkload.getWorkload() - nepuWorkload.getUsedWorkload(), UseMethodConst.DEDUCTTEACH);
//                workloadUseLogList.add(teachTargetLog);
//                nepuWorkload.setUsedWorkload(nepuWorkload.getWorkload());
//                nepuWorkload.setUsedUp(1);
//                nepuWorkloadService.updateOne(nepuWorkload);
////                System.out.println("workload:" + workload);
//            }
//            //若本条教学工作量记录全部使用会超过目标教学工作量
//            else {
//                WorkloadUseLog teachTargetLog = teachUseLog(nepuWorkload.getCycleId(),userId,teachTargetWorkload - teachworkload,UseMethodConst.DEDUCTTEACH);
//                workloadUseLogList.add(teachTargetLog);
//                nepuWorkload.setUsedWorkload(nepuWorkload.getUsedWorkload() + teachTargetWorkload - teachworkload);
//                nepuWorkloadService.updateOne(nepuWorkload);
//            }
//
//        }
//        System.out.println("workloadUseLogList:"+workloadUseLogList);
//        logService.saveList(workloadUseLogList);
//        return;
//    }


    @WebLog(module = "nepu-access",operate = MethodTypeConst.UPDATE)
    @Transactional
    @PostMapping("workloads/{workloadId}/unlock")
    @ApiOperation(value = "工作量解锁",notes = "收回已分配工作量")
    public ResponseDTO<Object> unlockWorkload(@PathVariable("workloadId") String workloadId){
        Optional<NepuWorkload> workloadOp = nepuWorkloadService.getById(workloadId);
        if (!workloadOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        NepuWorkload workload = workloadOp.get();
        // 解锁校验
        if (!workload.getWorkloadType().equals(WorkloadTypeConst.RESEARCH)){
            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"仅支持科研工作量解锁");
        }
        // 查询分配的工作量是否被使用
        JSONObject jsonObject = JSONObject.parseObject(workload.getWorkloadAttach());
        //System.out.println("jsonObject.getString()"+jsonObject.getString("researchId"));
        List<NepuWorkload> workloadList = nepuWorkloadService.getLinkList(workload.getLinkId());
        Double allUsed = 0.0;
        Double allAssign = 0.0;
        List<String> assignIds = new ArrayList<>();
        for (NepuWorkload item:workloadList){
            if (!item.getId().equals(workloadId)){
                allUsed += item.getUsedWorkload();
                allAssign += item.getWorkload();
                assignIds.add(item.getId());
            }
        }
        // 分配工作量并未被使用
        if (allUsed.equals(0.0)){
            // 清除全部非自己的内容
            nepuWorkloadService.batchDelete(assignIds);
            workload.setUsedWorkload(workload.getUsedWorkload() - allAssign);
            // 锁 - 升级
            workload.setWorkloadLock(2);
            //workload.setDistributeAccess(1);
            nepuWorkloadService.updateOne(workload);
            return ResponseDTO.succMsg("收回成功");
        }else {
            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"已用于抵扣，无法收回");
        }
    }


    @WebLog(module = "nepu-access",operate = MethodTypeConst.UPDATE)
    @PostMapping(value = "workloads/distribute")
    @ApiOperation(value = "工作量分配(工作量ID)")
    public ResponseDTO distributeWorkload(@RequestBody DistributeDTO dto){
//        for (DistributeItem item:dto.getItems()){
//            List<NepuResearchWorkload> researchWorkloadList = service.findByUserIdAndResearchTypeAndCycleId(item.getUserId(),ResearchTypeConst.PAPER,cycleService.getNowCycleId());
//            System.out.println("item:"+item);
//            System.out.println("item.getUserId():"+item.getUserId());
//            Integer totalnumber=0;
//            for (NepuResearchWorkload nepuResearchWorkload : researchWorkloadList){
//                if (nepuResearchWorkload.getWorkload()!=0);
//                totalnumber++;
//            }
//            System.out.println("totalnumber"+totalnumber);
//            if (totalnumber>=3&&item.getWorkload()!=0){
//                return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"成员"+item.getUserId()+"本考核周期内的论文已有三篇获得工作量！");
//            }
//        }
        String researchWorkloadId = dto.getResearchWorkloadId();
        // 获取
        Optional<NepuWorkload> workloadOp = nepuWorkloadService.getById(researchWorkloadId);
        if (!workloadOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        // 获取负责人拥有的该项目workload
        NepuWorkload nepuWorkload = workloadOp.get();
        return nepuWorkloadService.distributeWorkload(dto,nepuWorkload);
    }

//    @PutMapping("workload/entity/redistribute")
//    @ApiOperation(value = "工作量再分配")
//    public ResponseDTO redistributeWorkload(@RequestBody ReDistributeDTO dto){
//        NepuResearchWorkload nepuResearchWorkload =
//                nepuResearchWorkloadDAO.findByMapperIdAndAndUserId(dto.getMapperId(),dto.getUserid());
//        DistributeDTO distributeDTO = new DistributeDTO();
//        distributeDTO.setItems(dto.getItems());
//        distributeDTO.setResearchWorkloadId(nepuResearchWorkload.getId());
//        return service.redistributeWorkload(dto,nepuResearchWorkload);
//    }


    @WebLog(module = "nepu-access",operate = MethodTypeConst.UPDATE)
    @PostMapping("workloads/entity/distribute")
    @ApiOperation(value = "工作量分配(实体ID)")
    public ResponseDTO distributeWorkload(@RequestBody @Validated EntityDistributeDTO dto){
        Optional<NepuWorkload> workloadOp = nepuWorkloadService.getAccessEntity(dto.getMapperId());
        if (!workloadOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"已分配或者资源不存在");
        }
        if (dto.getItems().size() == 0){
            return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,"请输入分配信息");
        }
//        for (DistributeItem item:dto.getItems()){
//            List<NepuResearchWorkload> researchWorkloadList = service.findByUserIdAndResearchTypeAndCycleId(item.getUserId(),ResearchTypeConst.PAPER,cycleService.getNowCycleId());
//            System.out.println("item"+item);
//            System.out.println("item.getUserId()"+item.getUserId());
//            Integer totalNumber=0;
//            for (NepuResearchWorkload nepuResearchWorkload : researchWorkloadList){
//                if (nepuResearchWorkload.getWorkload()!=0);
//                totalNumber++;
//            }
//            System.out.println("totalnumber"+totalNumber);
//            if (totalNumber>=3&&item.getWorkload()!=0){
//                return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"成员"+item.getUserId()+"本考核周期内的论文已有三篇获得工作量！");
//            }
//        }
//        System.out.println(workloadOp.get().getResearchType());
//        JSONObject jsonObject = JSONObject.parseObject(workloadOp.get().getWorkloadAttach());
//        if (jsonObject.getString("researchType").equals(ResearchTypeConst.PAPER)) {
//        }else{
        for (DistributeItem item : dto.getItems()) {
            if (item.getWorkload().equals(0.0)) {
                return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM, "分配工作量不可为0");
            }
        }

        DistributeDTO distributeDTO = new DistributeDTO();
        distributeDTO.setItems(dto.getItems());
        distributeDTO.setResearchWorkloadId(workloadOp.get().getId());
        return nepuWorkloadService.distributeWorkload(distributeDTO,workloadOp.get());
    }

    @GetMapping("workloads")
    @ApiOperation(value = "工作量记录查询")
    public ResponseDTO getWorkload(WorkloadQueryDTO dto){
        Sort sort;
        if(dto.getOrder().equalsIgnoreCase("DESC")){
            sort = Sort.by(Sort.Direction.DESC, dto.getSortBy());
        }else {
            sort = Sort.by(Sort.Direction.ASC, dto.getSortBy());
        }
        // tips : 页码对应 - 1
        Pageable pageable = PageRequest.of(dto.getPageNum() - 1 , dto.getPageSize(), sort);
        NepuWorkload workload = new NepuWorkload();
        BeanUtil.copyProperties(dto,workload, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        ExampleMatcher matcher = ExampleMatcher.matching();
        matcher = matcher.withMatcher("workloadAttach",ExampleMatcher.GenericPropertyMatchers.contains());
        Example<NepuWorkload> example = Example.of(workload,matcher);
        return ResponseDTO.succData(nepuWorkloadService.getAll(pageable,example));
        //return service.getAll(pageable,example);
    }

    @Transactional
    @GetMapping("workloads/analysis")
    @ApiOperation(value = "分析工作量获取情况",notes = "")
    public ResponseDTO analysisWorkload(@RequestParam(value = "userId",required = false) Long userId){
        if (Validator.isEmpty(userId)){
            userId = StpUtil.getLoginIdAsLong();
        }
        List<WorkloadCountVO> countVOS = new ArrayList<>();
        countVOS.add(nepuWorkloadService.buildWorkloadCount(ResearchTypeConst.AWARD,userId,0));
        countVOS.add(nepuWorkloadService.buildWorkloadCount(ResearchTypeConst.BOOK,userId,0));
        countVOS.add(nepuWorkloadService.buildWorkloadCount(ResearchTypeConst.PAPER,userId,0));
        countVOS.add(nepuWorkloadService.buildWorkloadCount(ResearchTypeConst.PROPERTY,userId,0));
        countVOS.add(nepuWorkloadService.buildWorkloadCount(ResearchTypeConst.SUBJECT,userId,0));
        countVOS.add(nepuWorkloadService.buildWorkloadCount(ResearchTypeConst.THINKTANK,userId,0));
        countVOS.add(nepuWorkloadService.buildWorkloadCount(ResearchTypeConst.TOPIC,userId,0));
        return ResponseDTO.succData(countVOS);
    }

//
//    @GetMapping(value = "workloads")
//    @ApiOperation(value = "查询全部",notes = "")
//    public ResponseDTO getAll(NepuWorkloadQueryDTO nepuWorkloadQueryDTO){
//
//        Sort sort;
//        if(nepuWorkloadQueryDTO.getOrder().equalsIgnoreCase("DESC")){
//            sort = Sort.by(Sort.Direction.DESC, nepuWorkloadQueryDTO.getSortBy());
//        }else {
//            sort = Sort.by(Sort.Direction.ASC, nepuWorkloadQueryDTO.getSortBy());
//        }
//
//        // tips : 页码对应 - 1
//        Pageable pageable = PageRequest.of(nepuWorkloadQueryDTO.getPageNum() - 1 , nepuWorkloadQueryDTO.getPageSize(), sort);
//
//        NepuWorkload nepuWorkload = new NepuWorkload();
//        BeanUtil.copyProperties(nepuWorkloadQueryDTO,nepuWorkload, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
//        Example<NepuWorkload> example = Example.of(nepuWorkload);
//
//        return ResponseDTO.succData(nepuWorkloadService.getAll(pageable,example));
//    }

    /**
     * 初始化构建
     * @param workload
     * @return
     */
    NepuWorkload initWorkload(NepuWorkload workload){
        workload.setUsedUp(0);
        workload.setUsedWorkload(0.0);
        return workload;
    }

    //@WebLog(module = "nepu-access")
    @PostMapping(value = "workloads")
    @ApiOperation(value = "新建记录",notes = "")
    //@SaCheckRole("super")
    public ResponseDTO saveOne(@RequestBody @Validated NepuWorkloadAddDTO nepuWorkloadAddDTO){
        NepuWorkload nepuWorkload = new NepuWorkload();
        nepuWorkload = initWorkload(nepuWorkload);
        BeanUtil.copyProperties(nepuWorkloadAddDTO,nepuWorkload,CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
//        BigDecimal workLoad = new BigDecimal(nepuWorkloadAddDTO.getWorkload());
//        nepuWorkload.setWorkload(workLoad.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        nepuWorkload.setWorkload(nepuWorkload.getWorkload());
        return ResponseDTO.succData(nepuWorkloadService.saveOne(nepuWorkload));
    }

    @GetMapping("workloads/{id}")
    @ApiOperation(value = "查询单条记录",notes = "传入ID")
    public ResponseDTO getOne(@PathVariable("id") String id){
        Optional<NepuWorkload> nepuWorkloadOp = nepuWorkloadService.getById(id);
        if(!nepuWorkloadOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"ID:["+id+"]对应的数据不存在");
        return ResponseDTO.succData(nepuWorkloadOp.get());
    }

    @WebLog(module = "nepu-access",operate = MethodTypeConst.DELETE)
    @DeleteMapping("workloads/{id}")
    @ApiOperation(value = "删除单条记录",notes = "传入ID")
    public ResponseDTO deleteOne(@PathVariable("id") String id){
        return nepuWorkloadService.deleteById(id);
    }

    @WebLog(module = "nepu-access",operate = MethodTypeConst.UPDATE)
    @PutMapping("workloads")
    @ApiOperation(value = "更新单条记录",notes = "")
    @SaCheckRole("admin")
    public ResponseDTO updateOne(@RequestBody @Validated NepuWorkloadUpdateDTO nepuWorkloadUpdateDTO){
        Optional<NepuWorkload> nepuWorkloadOp = nepuWorkloadService.getById(nepuWorkloadUpdateDTO.getId());
        if (!nepuWorkloadOp.isPresent()){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        }
        NepuWorkload nepuWorkload = nepuWorkloadOp.get();
        BeanUtil.copyProperties(nepuWorkloadUpdateDTO,nepuWorkload,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
//        BigDecimal workLoad = new BigDecimal(nepuWorkloadUpdateDTO.getWorkload());
//        nepuWorkload.setWorkload(workLoad.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        nepuWorkload.setWorkload(nepuWorkload.getWorkload());
        return ResponseDTO.succData(nepuWorkloadService.updateOne(nepuWorkload));
    }

    @GetMapping("workloads/{id}/part")
    @ApiOperation(value = "查询参与人员(id)",notes = "")
    public ResponseDTO getParticipantByWorkload(@PathVariable("id") String id){
        Optional<NepuWorkload> workloadOp = nepuWorkloadService.getById(id);
        if (!workloadOp.isPresent())
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
        NepuWorkload workload = workloadOp.get();
        ResearchAttach attach = JsonUtil.string2Obj(workload.getWorkloadAttach(),ResearchAttach.class);
        if (Validator.isNotEmpty(attach)){
            assert attach != null;
            String researchType = attach.getResearchType();
            Optional<Object> objOp = researchServiceCtl.getById(workload.getLinkId(),researchType);
            if (!objOp.isPresent())
                return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"未找到关联实体");
            List<Long> userIds = new ArrayList<>();
            if (researchType.equals(ResearchTypeConst.PAPER)){
                NepuPaper paper = (NepuPaper) objOp.get();

            }
            else if (researchType.equals(ResearchTypeConst.AWARD)){
                NepuAward award = (NepuAward) objOp.get();
                userIds = award.getUserIdList();
            }
            else if (researchType.equals(ResearchTypeConst.THINKTANK)){
                NepuThinkTank thinkTank = (NepuThinkTank) objOp.get();
                userIds = thinkTank.getUserIdList();
            }
            else if (researchType.equals(ResearchTypeConst.TOPIC)){
                NepuTopic topic = (NepuTopic) objOp.get();
                userIds = topic.getUserIdList();
            }
            else if (researchType.equals(ResearchTypeConst.BOOK)){
                NepuBook book = (NepuBook) objOp.get();
                userIds = book.getUserIdList();
            }
            else if (researchType.equals(ResearchTypeConst.PROPERTY)){
                NepuProperty property = (NepuProperty) objOp.get();
            }
            else if (researchType.equals(ResearchTypeConst.SUBJECT)){
                NepuSubject subject = (NepuSubject) objOp.get();
                userIds = subject.getUserIdList();
            }
            List<SysUser> users = userService.findByIds(userIds);
            List<SysUserBasic> userBasics = new ArrayList<>();
            users.forEach(user -> {
                SysUserBasic basic = userService.buildBasic(user);
                userBasics.add(basic);
            });
            return ResponseDTO.succData(userBasics);

        }else {
            return ResponseDTO.wrap(ResponseCodeConst.SYSTEM_ERROR,"附加信息解析失败");
        }
    }

    @GetMapping("workloads/part")
    @ApiOperation(value = "查询参与人员(linkId)",notes = "根据传入的科研记录ID查询")
    public ResponseDTO getParticipantByParams(
            @RequestParam("linkId") String linkId
    ){
        Optional<NepuWorkload> workloadOp = nepuWorkloadService.getLinkEntity(linkId);
        if (!workloadOp.isPresent())
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"未找到对应关联信息");
        NepuWorkload workload = workloadOp.get();
        ResearchAttach attach = JsonUtil.string2Obj(workload.getWorkloadAttach(),ResearchAttach.class);
        if (Validator.isNotEmpty(attach)){
            assert attach != null;
            String researchType = attach.getResearchType();
            Optional<Object> objOp = researchServiceCtl.getById(linkId,researchType);
            if (!objOp.isPresent())
                return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"未找到关联实体");
            List<Long> userIds = new ArrayList<>();
            if (researchType.equals(ResearchTypeConst.PAPER)){
                NepuPaper paper = (NepuPaper) objOp.get();

            }
            else if (researchType.equals(ResearchTypeConst.AWARD)){
                NepuAward award = (NepuAward) objOp.get();
                userIds = award.getUserIdList();
            }
            else if (researchType.equals(ResearchTypeConst.THINKTANK)){
                NepuThinkTank thinkTank = (NepuThinkTank) objOp.get();
                userIds = thinkTank.getUserIdList();
            }
            else if (researchType.equals(ResearchTypeConst.TOPIC)){
                NepuTopic topic = (NepuTopic) objOp.get();
                userIds = topic.getUserIdList();
            }
            else if (researchType.equals(ResearchTypeConst.BOOK)){
                NepuBook book = (NepuBook) objOp.get();
                userIds = book.getUserIdList();
            }
            else if (researchType.equals(ResearchTypeConst.PROPERTY)){
                NepuProperty property = (NepuProperty) objOp.get();
            }
            else if (researchType.equals(ResearchTypeConst.SUBJECT)){
                NepuSubject subject = (NepuSubject) objOp.get();
                userIds = subject.getUserIdList();
            }
            List<SysUser> users = userService.findByIds(userIds);
            List<SysUserBasic> userBasics = new ArrayList<>();
            users.forEach(user -> {
                SysUserBasic basic = userService.buildBasic(user);
                userBasics.add(basic);
            });
            return ResponseDTO.succData(userBasics);

        }else {
            return ResponseDTO.wrap(ResponseCodeConst.SYSTEM_ERROR,"附加信息解析失败");
        }



//        List<Long> userIds = new ArrayList<>();
//        if (researchType.equals(ResearchTypeConst.PAPER)){
//            return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,"论文不需要分配工作量");
//        }
//        else if (researchType.equals(ResearchTypeConst.AWARD)){
//            Optional<Object> awardOp = researchServiceCtl.getById(mapperId,ResearchTypeConst.AWARD);
//            if (!awardOp.isPresent())
//                return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
//            Optional<Object> nepuAwardOp =  researchServiceCtl.getById(mapperId,ResearchTypeConst.AWARD);
//            NepuAward award = new NepuAward();
//            BeanUtil.copyProperties(nepuAwardOp.get(),award, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
//            userIds = award.getUserIdList();
//        }
//        else if (researchType.equals(ResearchTypeConst.THINKTANK)){
//            Optional<Object> thinkTankOp = researchServiceCtl.getById(mapperId,ResearchTypeConst.THINKTANK);
//            if (!thinkTankOp.isPresent())
//                return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
//            Optional<Object> nepuThinkTankOp =  researchServiceCtl.getById(mapperId,ResearchTypeConst.THINKTANK);
//            NepuThinkTank thinkTank = new NepuThinkTank();
//            BeanUtil.copyProperties(nepuThinkTankOp.get(),thinkTank, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
//            userIds = thinkTank.getUserIdList();
//        }
//        else if (researchType.equals(ResearchTypeConst.TOPIC)){
//            Optional<Object> topicOp = researchServiceCtl.getById(mapperId,ResearchTypeConst.TOPIC);
//            if (!topicOp.isPresent())
//                return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
//            Optional<Object> nepuTopicOp =  researchServiceCtl.getById(mapperId,ResearchTypeConst.TOPIC);
//            NepuTopic topic = new NepuTopic();
//            BeanUtil.copyProperties(nepuTopicOp.get(),topic, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
//            userIds = topic.getUserIdList();
//        }
//        else if (researchType.equals(ResearchTypeConst.BOOK)){
//            Optional<Object> bookOp = researchServiceCtl.getById(mapperId,ResearchTypeConst.BOOK);
//            if (!bookOp.isPresent())
//                return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
//            Optional<Object> nepuBookOp =  researchServiceCtl.getById(mapperId,ResearchTypeConst.BOOK);
//            NepuBook book = new NepuBook();
//            BeanUtil.copyProperties(nepuBookOp.get(),book, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
//            userIds = book.getUserIdList();
//        }
//        else if (researchType.equals(ResearchTypeConst.PROPERTY)){
//            return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM,"知识产权不需要分配工作量");
//        }
//        else if (researchType.equals(ResearchTypeConst.SUBJECT)){
//            Optional<Object> subjectOp = researchServiceCtl.getById(mapperId,ResearchTypeConst.SUBJECT);
//            if (!subjectOp.isPresent())
//                return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND);
//            Optional<Object> nepuSubjectOp =  researchServiceCtl.getById(mapperId,ResearchTypeConst.SUBJECT);
//            NepuSubject subject = new NepuSubject();
//            BeanUtil.copyProperties(nepuSubjectOp.get(),subject, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
//            userIds = subject.getUserIdList();
//        }
//        List<SysUser> users = userService.findByIds(userIds);
//        List<SysUserBasic> userBasics = new ArrayList<>();
//        users.forEach(user -> {
//            SysUserBasic basic = userService.buildBasic(user);
//            userBasics.add(basic);
//        });
//        return ResponseDTO.succData(userBasics);
    }


}
